package com.ccys.cms.service.productAndService.impl;

import cn.hutool.core.util.IdUtil;
import com.ccys.cms.service.productAndService.PackageDetailService;
import com.ccys.cms.service.productAndService.PackageService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.web.productAndService.BatchPackageDetailDto;
import com.ccys.db.dto.web.productAndService.PackageDto;
import com.ccys.db.entity.TblPackage;
import com.ccys.db.entity.TblPackageDetail;
import com.ccys.db.mapper.TblPackageMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.vo.web.productAndService.PackageVo;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class PackageServiceImpl extends BaseServiceImpl<TblPackage> implements PackageService {


    @Resource
    private TblPackageMapper mapper;

    @Resource
    private PackageDetailService packageDetailService;

    @Override
    public ResponseResult getPage(PackageDto dto) {
        PageDto.startPage();
        List<PackageVo> list = mapper.getList(dto);
        PageInfo<PackageVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult change(BatchPackageDetailDto dto) {

        //修改时删除之前的packagedetail
        String id = dto.getId();
        List<TblPackageDetail> detailList = dto.getDetailList();
        if (StringUtils.isNotEmpty(id)) {
            packageDetailService.deletePackageDetails(id);
        }

        int i = this.insertOrUpdate(dto);
        if(CollectionUtils.isNotEmpty(detailList)){
            detailList.forEach(x -> {
                x.setPackageId(dto.getId());
                x.setCreatedOnUtc(new Date().getTime());
                x.setCreatedBy(UserUtil.getCurLoginUserId());
                x.setId(IdUtil.getSnowflakeNextIdStr());
            });
            packageDetailService.insertAll(detailList);
        }
        //批量添加packageDetail
        return ResponseResult.update(i);
    }
}
